package com.isasc.demo.pooled.itemqueue;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: ywy
 * @date: 2023-01-31
 * @desc: 1. 空闲对象池和使用对象池
 * 2. 最大数量控制
 * 3. 有入有出
 */
@Slf4j
public class RecallQueue<T extends QueueItem> {

    //todo
    private int front; //已召回队头
    private int rear; //已召回队尾
    private int maxSize = 8;
    private QueueItem[] doneRecallQueue; //已召回队列


    public RecallQueue(int maxSize) {
        this.maxSize = maxSize;

        // todo
        front = rear = 0; //队首队尾重合，且指向0
        doneRecallQueue = new QueueItem[maxSize]; //已召回队列
    }

    public T recallQueue(Class<T> clazz) throws Exception {
        //todo
        if (rear != front) {
            //若已召回队列不为空，则将队首物品移出，同时召回新物品
            front = (front + 1) % maxSize;
        }
        QueueItem obj = T.init();
        return (T) obj;
    }

    public void returnQueue(T obj) {
        //todo
        if ((rear + 1) % maxSize == front) {
            throw new RuntimeException("doneRecallQueue is full, can't return again!");
        }
        //将已召回的物品插入已召回队列的队尾
        rear = (rear + 1) % maxSize;
        doneRecallQueue[rear] = obj;
    }
}
